package com.ankiang.mykeys;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ankiang.mykeys.common.Constant;
import com.ankiang.utils.DBManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MainActivity extends AppCompatActivity implements SearchView.SearchViewListener {

    final static String TAG = "MainActivity";

    /**
     * 搜索结果列表view
     */
    private ListView lvResults;

    /**
     * 搜索view
     */
    private SearchView searchView;


    /**
     * 热搜框列表adapter
     */
    private ArrayAdapter<String> hintAdapter;

    /**
     * 自动补全列表adapter
     */
    private ArrayAdapter<Object> autoCompleteAdapter;

    /**
     * 搜索结果列表adapter
     */
    private SearchAdapter resultAdapter;

    /**
     * 数据库数据，总数据
     */
    private List<SearchBean> dbData;

    /**
     * 热搜版数据
     */
    private List<String> hintData;

    /**
     * 搜索过程中自动补全数据
     */
    private List<Object> autoCompleteData;

    /**
     * 搜索结果的数据
     */
    private List<SearchBean> resultData;

    /**
     * 默认提示框显示项的个数
     */
    private static int DEFAULT_HINT_SIZE = 6;

    /**
     * 提示框显示项的个数
     */
    private static int hintSize = DEFAULT_HINT_SIZE;


    private DBManager dbManager;

    /**
     * 设置提示框显示项的个数
     *
     * @param hintSize 提示框显示个数
     */
    public static void setHintSize(int hintSize) {
        MainActivity.hintSize = hintSize;
    }


    Fragment home;
    Fragment explore;
    Fragment fav;
    Fragment me;

    RadioGroup myTabRg;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);


        initView();
        //FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void initView() {


        dbManager = new DBManager(this.getApplicationContext());

        lvResults = (ListView) findViewById(R.id.main_lv_search_results);
        searchView = (SearchView) findViewById(R.id.main_search_layout);
        //设置监听
        searchView.setSearchViewListener(this);
        //设置adapter
        searchView.setTipsHintAdapter(hintAdapter);
        searchView.setAutoCompleteAdapter(autoCompleteAdapter);

        lvResults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Toast.makeText(MainActivity.this, position + "", Toast.LENGTH_SHORT).show();
            }
        });


        home = new FragmentHome();
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, home).commit();
        dbManager.update(Constant.K_CURRENT_DATA, Constant.K_PAGE_HOME);
        initData();
        myTabRg = (RadioGroup) findViewById(R.id.tab_menu);
        myTabRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {


            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                switch (checkedId) {
                    case R.id.rbHome:
                        home = new FragmentHome();
                        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, home)
                                .commit();
                        dbManager.update(Constant.K_CURRENT_DATA, Constant.K_PAGE_HOME);
                        initData();
                        Log.i("MyFragment", "rbHome");
                        break;
                    case R.id.rbExplore:
                        explore = new FragmentExplore();
                        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, explore)
                                .commit();
                        initData();
                        dbManager.update(Constant.K_CURRENT_DATA, Constant.K_PAGE_EXPLORE);
                        Log.i("MyFragment", "rbExplore");
                        break;
                    case R.id.rbMe:
                        me = new FragmentMe();
                        initData();
                        dbManager.update(Constant.K_CURRENT_DATA, Constant.K_PAGE_ME);
                        Log.i("MyFragment", "rbMe");
                        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, me)
                                .commit();
                        break;
                    default:
                        break;
                }

            }
        });
    }


    /**
     * 初始化数据
     */
    private void initData() {
        //从数据库获取数据
        getDbData();
        //初始化热搜版数据
        getHintData();
        //初始化自动补全数据
        getAutoCompleteData(null);
        //初始化搜索结果数据
        getResultData(null);
    }

    /**
     * 获取db 数据
     */
    private void getDbData() {
        int size = 100;
        dbData = new ArrayList<>(size);

        String key = dbManager.get(Constant.K_CURRENT_DATA);
        String json = dbManager.get(key);
        Log.i(TAG, "key=" + key);


        try {
            JSONArray mData = Utils.getJsonArray(key, json);

            Log.i(TAG, "json=" + mData.toString());
            for (int i = 0; i < mData.length(); i++) {
                JSONObject obj = (JSONObject) mData.get(i);
                int iconId = Utils.getIntFromJson(obj, "icon");
                String title = Utils.getStringFromJson(obj, "title");
                String content = Utils.getStringFromJson(obj, "content");
                String comments = Utils.getStringFromJson(obj, "comments");
                dbData.add(new SearchBean(iconId, title, content, comments));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取热搜版data 和adapter
     */
    private void getHintData() {
        hintData = new ArrayList<>(hintSize);
        for (int i = 1; i <= hintSize; i++) {
            hintData.add("热搜版" + i + "：Android自定义View");
        }
        hintAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, hintData);
    }

    /**
     * 获取自动补全data 和adapter
     */
    private void getAutoCompleteData(String text) {
        Log.i(TAG, "正在自动提示...");

        Log.i(TAG, "keyword text="+text);

        if (text == null){
            Log.e(TAG, "关键词没有取到！！！");
            return;
        }


        String str = text.trim().toLowerCase();
        if (autoCompleteData == null) {
            //初始化
            autoCompleteData = new ArrayList<>(hintSize);
        } else {
            Log.i(TAG, "dbData.size()=" + dbData.size());
            Log.i(TAG, "hintSize=" + hintSize);
            // 根据text 获取auto data
            autoCompleteData.clear();
            for (int i = 0, count = 0; i < dbData.size()
                    && count < hintSize; i++) {
                String title = dbData.get(i).getTitle().toLowerCase();

                Log.i(TAG, "title=" + title);
                Log.i(TAG, "count=" + count);
                Log.i(TAG, "keyword text="+str);
                Log.i(TAG, "title.contains(str)="+title.contains(str));

                Log.i(TAG, "test="+(title != null && str != null && title.contains(str)));

                if (title != null && str != null && title.contains(str)) {
                    autoCompleteData.add(title);
                    count++;
                }
            }
        }
        if (autoCompleteAdapter == null) {
            autoCompleteAdapter = new ArrayAdapter<>(this, R.layout.search_item, autoCompleteData);
        } else {
            autoCompleteAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取搜索结果data和adapter
     */
    private void getResultData(String text) {
        if (resultData == null) {
            // 初始化
            resultData = new ArrayList<>();
        } else {
            resultData.clear();
            if (text != null ) {
                for (int i = 0; i < dbData.size(); i++) {
                    if (dbData.get(i).getTitle().contains(text.trim())) {
                        resultData.add(dbData.get(i));
                    }
                }
            }
        }
        if (resultAdapter == null) {
            resultAdapter = new SearchAdapter(this, R.id.search_item_info, R.layout.search_item, autoCompleteData);
        } else {
            resultAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 当搜索框 文本改变时 触发的回调 ,更新自动补全数据
     *
     * @param text
     */
    @Override
    public void onRefreshAutoComplete(String text) {
        //更新数据
        getAutoCompleteData(text);
    }

    /**
     * 点击搜索键时edit text触发的回调
     *
     * @param text
     */
    @Override
    public void onSearch(String text) {
        //更新result数据
        getResultData(text);
        lvResults.setVisibility(View.VISIBLE);
        //第一次获取结果 还未配置适配器
        if (lvResults.getAdapter() == null) {
            //获取搜索数据 设置适配器
            lvResults.setAdapter(resultAdapter);
        } else {
            //更新搜索数据
            resultAdapter.notifyDataSetChanged();
        }
        Toast.makeText(this, "完成搜素", Toast.LENGTH_SHORT).show();
    }








//
//
//    class MySearchAdapter extends ArrayAdapter<SearchItem> {
//        private int mResourceId;
//
//        public MySearchAdapter(Context context, int textViewResourceId) {
//            super(context, textViewResourceId);
//            this.mResourceId = textViewResourceId;
//        }
//
//        @Override
//        public View getView(int position, View convertView, ViewGroup parent) {
//            SearchItem item = getItem(position);
//            LayoutInflater inflater = getLayoutInflater();
//            View view = inflater.inflate(mResourceId, null);
//            TextView titleText = (TextView) view.findViewById(R.id.title);
//            TextView contentText = (TextView) view.findViewById(R.id.content);
//            TextView commentText = (TextView) view.findViewById(R.id.comments);
//
//            titleText.setText(item.getTitle());
//            contentText.setText(item.getComments());
//            commentText.setText(item.getContent());
//
//            return view;
//        }
//    }
//
//    class SearchItem {
//        private String title;
//        private String content;
//        private String comments;
//
//        public SearchItem(String title, String content, String comments) {
//            this.comments = comments;
//            this.title = title;
//            this.content = content;
//        }
//
//        public String getTitle() {
//            return this.title;
//        }
//
//        public String getComments() {
//            return this.comments + "";
//        }
//
//        public String getContent() {
//            return this.content;
//        }
//    }






}
